package vip.zhenzicheng.design_patterns.singleton.lazy;

/**
 * 最佳解决方式 DCL + volatile
 *
 * @author zhenzicheng
 * @date: 2022-05-24 23:24
 */
public class Singleton {
  /**
   * 禁止指令重排与内存可见
   */
  private static volatile Singleton INSTANCE;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (INSTANCE == null) {
      synchronized (Singleton.class) {
        if (INSTANCE == null) {
          INSTANCE = new Singleton(); // 指令重排可能导致线程访问到初始中间阶段null值
        }
      }
    }
    return INSTANCE;
  }
}
